<template>
	<view class="container" :class="disableScroll?'disable-scroll':''">
		<!-- 就餐方式 -->
		<view v-show="dineTypeVisable" id="dine-type-box" class="d-flex flex-row justify-content-between align-items-center font-size-28 m-16 p-20 b-r-14 bg-white">
			<view class="">
				<view v-if="dineType == 'in'">伊香牛肉面-福州大道</view>
				<view v-else>店铺营业时间</view>
			</view>
			<view class=" d-flex flex-row align-items-center dine-switch">
				<view class="type" @click="changeDineType('in')" :class="dineType=='in'?'active':''">店内</view>
				<view class="type" @click="changeDineType('out')" :class="dineType=='out' ? 'active' : ''">预定打包</view>
			</view>
		</view>
			
		<!-- 美食分类 -->
		<scroll-view :scroll-into-view="toTopCateView" scroll-x enable-flex class="category-view bg-white" id="category-list-box">
			<view :id="'top-cate-'+item.id" class="d-inline p-20"
				v-for="(item, index) in categories" :key="item.id"
				:class="currentCategoryId ? (currentCategoryId==item.id ? 'active' : '') : (index == 0 ? 'active' : '')"
				@click="changeCategory(item)">{{ item.name }}</view>
		</scroll-view>
		
		<!-- 商品列表 -->
		<scroll-view scroll-y enable-flex acceleration show-scrollbar="false"   
			class="product-list"
			:scroll-into-view="toView"
			scroll-with-animation
			@scrolltoupper="productScrollToUpper()"
			@scroll="productScroll"
		>
			<template v-for="(category, index) in categories">
				<view class="cate-box" :key="category.id">
					<view class="d-flex flex-column align-items-center">
						<view :id="'cate'+category.id" class="cate-title">{{category.name}}</view>
					</view>
					<view  class="d-flex flex-row flex-wrap">
						<view
							v-for="(item,i) in category['products']" 
							:key="item.id" 
							class="product-box d-flex flex-column bg-white">
							<image class="product-img" :src="item.photo" lazy-load></image>
							<view class="product-detail d-flex flex-column justify-content-between m-12">
								<view class="text-line-2">{{ item.name }}</view>
								<view class="d-flex flex-row justify-content-between">
									<view class="font-color-red">￥{{ item.price }}</view>
									<view v-if="item.children.length>0" @click="openSpecModelVisable(item)" class="bg-theme font-color-white r-15 font-size-24 select-prop">选规格</view>
									<view v-else class="d-flex flex-row align-items-center">
										<view v-if="shopCartSimpleItems[item.id]" @click="subSimpleProduct(item,index,i)" class="sub-button">-</view>
										<view v-if="shopCartSimpleItems[item.id]" class="quantity font-size-28">{{shopCartSimpleItems[item.id]}}</view>
										<view @click="addSimpleProduct(item,index,i)" class="add-button">+</view>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
				
			</template>
		</scroll-view>
		
		
		<!-- 商品规格弹窗 -->
		<view class="cover" v-show="specCoverVisable" @click="closeSpecDialog" title="遮罩层"></view>
		<view class="model" v-show="specModelVisable" title="弹窗">
			<view class="model-header d-flex flex-row justify-content-between m-b-40">
				<view class="d-flex flex-row">
					<image class="product-img" :src="currentProduct.photo"></image>
					<view class="d-flex flex-column justify-content-evenly">
						<view class="">{{currentProduct.name}}</view>
						<view class="amount">月销量：{{currentProduct.sale_quantity}}</view>
						<view class="font-color-red">￥{{currentProduct.price}}</view>
					</view>
				</view>
				<image @click="closeSpecDialog" src="../../static/close.png" class="close-buttom"></image>
			</view>
			
			<scroll-view class="spec-scroll-box" scroll-y enable-flex>
				<view  v-for="(cate,key1) in currentProduct.children" :key="key1" class="d-flex flex-column m-b-20">
					<view class="spec-cate-title m-b-20" title="规格分类名称">{{cate.category_name}}</view>
					<view class="d-flex flex-row flex-wrap">
						<view 
							v-for="(item,key2) in cate.children" :key="key2" 
							@click="selectSpec(key1, key2)" 
							:class="item.selected ? 'spec-button-selected' : ''"
							class="spec-button">
							{{item.name}}{{Math.floor(item.price)}}元
						</view>
					</view>
				</view>
			</scroll-view>
			
			<view @click="addCart()" class="add-cart-button">加入购物车</view>
		</view>
		
		<!-- 购物车汇总 弹窗 -->
		<view v-show="cartDialogVisable && shopCartTotal.quantity" class="cart-dialog-button d-flex flex-row justify-content-between">
			<view  @click="openCartDialogList()" class="d-flex flex-row align-items-center">
				<view class="left item-flex-center">
					<image class="cart-icon" src="../../static/cart.png"></image>
					<view class="quantity">{{ shopCartTotal.quantity }}</view>
				</view>
				<view class="total-money font-color-white item-flex-center m-l-20">￥{{shopCartTotal.money.toFixed(2)}}</view>
			</view>
			<view @click="submit()" class="submit item-flex-center">选好了</view>
		</view>
		
		<!-- 购物车列表 -->
		<view v-show="cartDialogListVisable && shopCartTotal.quantity" class="cart-dialog-list-box">
			<view class="cover" @click="closeCartDialogList()"></view>
			<view class="model">
				<view class="d-flex flex-row justify-content-between align-items-center header ">
					<view class="font-color-theme">购物车</view>
					<view @click="emptyCart()" class="d-flex flex-row align-items-center">
						<image class="img-30 m-r-5" src="../../static/empty.png"></image>
						<view class="font-color-gray font-size-24" style="line-height: 24rpx;">清空</view>
					</view>
				</view>
				<view class="list p-16">
					<template v-for="(item,index) in shopCartItems">
						<view v-if="item.quantity" :key="index" class="d-flex flex-row justify-content-between align-items-center item">
							<view class="d-flex flex-column w-50">
								<view>{{item.name}}</view>
								<view class="text-line-1 font-size-28 font-color-gray">{{item.prop_text}}</view>
							</view>
							<view class="d-flex flex-row align-items-center w-50 justify-content-between">
								<view class="font-color-red font-size-28 w-50">￥{{item.total_price.toFixed(2)}}</view>
								<view class="d-flex flex-row align-items-center w-50">
									<view @click="subQuantity(item)" class="sub-button">-</view>
									<view class="quantity font-size-28">{{item.quantity}}</view>
									<view @click="addQuantity(item)" class="add-button">+</view>
								</view>
							</view>
						</view>
					</template>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {uniBadge} from '@dcloudio/uni-ui'
	import {mapState,mapMutations,mapGetters} from 'vuex' 
	import {getProducts} from '../../api/product.js'
	import {submitOrder} from '../../api/order.js'
	const _ = require('lodash')
	
	export default {
		name: "menu",
		components: {
			uniBadge
		},
		data() {
			return {
				dineType: 'in',
				dineTypeVisable: true,
				currentCategoryId: '',
				categories: [],
				products: [],
				disableScroll: false,
				specCoverVisable: false,
				specModelVisable: false,
				cartDialogVisable: false,
				cartDialogListVisable: false,
				currentProduct: {},
				toTopCateView: '',
				toView: '',
				cateHeightList:[],
			}
		},
		computed: {
			...mapGetters({
				//购物车汇总信息
				shopCartTotal: 'shopCartTotal'
			}),
			...mapState({
				//购物车列表数量
				shopCartItems: state => state.shopCart.items,
				//购物车中的简单商品：列表出现 “+”号的商品
				shopCartSimpleItems: state => state.shopCart.simple_items,
			})
		},
		onLoad() {
			this.init();
		},
		mounted() {
			
		},
		methods: {
			...mapMutations([
				'productAddCart',
				'productEmptyCart',
				'subQuantity',
				'addQuantity',
			]),
			init(){
				getProducts().then((data)=>{
					this.categories = data;
					this.$nextTick(()=>{
						this.calcCateHeight();
					})
				}).catch(err=>{
					
				});
			},
			changeDineType(type){
				this.dineType = type;
			},
			calcCateHeight(){
				//获取节点为 .cate-box 距离顶部的距离，返回值放在数组中，页面滚动时根据该数组判断是否需要切换分类
				const query = uni.createSelectorQuery().in(this);
				query
					.selectAll('.cate-box')
					.boundingClientRect()
					.exec(res => {
						let nodes = res[0];
						let rel = [];
						nodes.map(item => {
							rel.push(item.top)
						});
						this.cateHeightList = rel;
					})
			},
			changeCategory(item){
				this.dineTypeVisable = false;
				this.currentCategoryId = item.id;
				this.toView = 'cate'+item.id;
			},
			productScrollToUpper(){
				this.dineTypeVisable = true;
			},
			productScroll(e){
				let scorllTop = e.detail.scrollTop;
				if (e.detail.scrollTop > 10 && this.dineTypeVisable == true) {
					this.dineTypeVisable = false;
				}

				for (let i = 0; i < this.cateHeightList.length; i++) {
					let h1 = this.cateHeightList[i];//当前分类起始位置
					let h2 = this.cateHeightList[i+1];//下一个分类起始位置
					if (scorllTop >= h1 && scorllTop < h2) {
						this.toTopCateView = 'top-cate-' + this.categories[i].id;
						this.currentCategoryId = this.categories[i].id;
					}
					
					//解决滚动到最后选项不会选择的问题
					let length = this.cateHeightList.length;
					if (scorllTop >= this.cateHeightList[length - 1]) {
						this.toTopCateView = 'top-cate-' + this.categories[length - 1].id;
						this.currentCategoryId = this.categories[length - 1].id;
					}
				}
				
			},
			openSpecModelVisable(product){
				this.specCoverVisable = true;
				this.specModelVisable = true;
				this.disableScroll = true;
				//深拷贝对象
				_.defaultsDeep(this.currentProduct, product);
			},
			selectSpec(index1, index2){
				//将子商品设置为选中状态
				this.currentProduct['children'][index1]['children'][index2].selected = !this.currentProduct['children'][index1]['children'][index2].selected;
			},
			closeSpecDialog(){
				this.disableScroll = true;
				this.specCoverVisable = false;
				this.specModelVisable = false;
			},
			//购物车
			addCart(product = {}){
				this.disableScroll = true;
				this.cartDialogVisable = true;
				this.specCoverVisable = false;
				this.specModelVisable = false;
				
				//简单商品深拷贝对象
				if (product) {
					_.defaultsDeep(this.currentProduct, product);
				}
				
				this.productAddCart(this.currentProduct);
				this.currentProduct = {};
			},
			openCartDialogList(){
				this.cartDialogListVisable = true;
				this.disableScroll = false;
			},
			closeCartDialogList(){
				this.cartDialogListVisable = false;
				this.disableScroll = true;
			},
			emptyCart(){
				this.productEmptyCart();
				this.cartDialogVisable = false;
				this.cartDialogListVisable = false;
			},
			addSimpleProduct(item,c_index,p_index){
				this.addCart(item);
				item.selected = true;
				if (item.selected_quantity) {
					item.selected_quantity++
				} else {
					item.selected_quantity = 1;
				}
			},
			subSimpleProduct(item,c_index,p_index){
				let cartItem = {
					id: item.id,
					name: item.name,
					price: item.price,
					total_price: item.price,
					quantity: 1,
					prop_id: [],
					prop_text: '',
				}
				this.subQuantity(cartItem);
				if (item.selected_quantity>=1) {
					item.selected_quantity--
				} else {
					item.selected = false;
					item.selected_quantity = 0;
				}
			},
			
			//下单
			submit(){
				let form = {
					items: this.shopCartItems,
					dine_type: this.dineType == 'in' ? 1 : 2,
				}
				submitOrder(form).then(({order_id}) => {
					console.log('获取到的订单ID：',order_id);
					uni.navigateTo({
						url:`../order/pay?order_id=${order_id}`
					})
				}).catch(err => {
					
				})
				// uni.navigateTo({
				// 	url: "./scan"
				// })
			},
		}
	}
</script>

<style lang="scss" scoped>
	@import '@/assets/css/menu.scss'
</style>
